import React from 'react';
import { connect } from 'dva';
import { Divider } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BatchUpload from '../../components/BatchUpload/Index';
import StepItem from '../../components/BatchUpload/StepItem';
import FileUpload from '../../components/BatchUpload/Upload';
import Finish from '../../components/BatchUpload/Finish';
import ProtInfo from './ProtInfo';

@connect(({ changeprot, publicdata, loading }) => ({
  uploading: loading.effects['publicdata/uploadFile'],
  batchQuery: changeprot.batchQuery,
  fileId: publicdata.downloadFile.fileId,
  fileName: publicdata.downloadFile.fileName,
  currentStep: changeprot.currentStep,
  progressPercent: changeprot.progressPercent,
  resultInfo: changeprot.resultInfo,
  showProgress: changeprot.showProgress,
}))
class Batch extends React.PureComponent {
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'changeprot/updateQuery',
      payload: { progressPercent: 0 },
    });
  }

  componentWillUnmount() {
    this.clearModel();
  }

  // 重置model
  clearModel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'changeprot/updateModelData',
      payload: {
        showProgress: false,
        progressPercent: 0,
        currentStep: 0,
        batchQuery: {
          // 更换协议
          changeType: '1',
          oldSuppId: undefined, // 原供应商
          suppId: undefined,
          suppProtId: undefined,
        },
      },
    });
  };

  // 设置当前位置
  setCurrentstep = currentStep => {
    const { dispatch } = this.props;
    dispatch({
      type: 'changeprot/updateModelData',
      payload: { currentStep },
    });
    if (!currentStep) {
      dispatch({
        type: 'changeprot/updateModelData',
        payload: {
          showProgress: false,
          progressPercent: 0,
          currentStep: 0,
        },
      });
    }
  };

  // 下一步
  onNext = () => {
    const { dispatch, currentStep } = this.props;
    dispatch({
      type: 'changeprot/getDownloadInfo',
      payload: {},
    });
    this.setCurrentstep(currentStep + 1);
  };

  // 上传文件：需要携带参数即传：batchQuery
  uploadFile = formData => {
    const {
      batchQuery: { changeType, oldSuppId, suppId, suppProtId },
      dispatch,
    } = this.props;
    let uploadQuery = {
      changeType,
      oldSuppId: suppId,
      suppProtId,
    };
    if (changeType === '2') {
      uploadQuery = { ...uploadQuery, oldSuppId, suppId };
    }
    // 需要携带参数即传：batchQuery，不需要传参可省略
    Object.entries(uploadQuery).forEach(([key, value]) => {
      formData.append(key, value);
    });
    dispatch({
      type: 'changeprot/uploadFileWithProgress',
      payload: formData,
    }).then(res => {
      if (res.success) {
        dispatch({
          type: 'changeprot/updateModelData',
          payload: { showProgress: true },
        });
      }
    });
  };

  render() {
    const { fileId, fileName, uploading, batchQuery, location, dispatch, currentStep, showProgress, resultInfo, progressPercent } = this.props;
    return (
      <PageHeaderWrapper>
        <BatchUpload currentStep={currentStep}>
          <StepItem title="选择供应商协议">
            <ProtInfo
              batchQuery={batchQuery}
              onNext={value => this.onNext(value)}
              location={location}
            />
            <Divider dashed style={{ marginTop: 100 }} />
            <p style={{ margin: '0 auto', width: '90%', fontSize: 14 }}>
              注：
              <br />
              1、上传人员当前的供应商协议产品不能超过新协议的产品范围，并且人员的产品执行地在新协议中存在。
              <br />
              2、更换供应商协议默认从本月开始生效，如果供应商发生变化，则生成原供应商的减员任务和新供应商的增员任务，其中社保公积金的生效日期按照地区申报政策（当月申报当月，生效日期为当月；当月申报次月，生效日期为次月）判断，；如果只是价格变化，则只生成调整任务。
              <br />
              3、上传的人员中在增员任务中存在待接单的数据（任务类型是入职增员、增加产品的任务、更换协议任务），则不允许更换，并计入到错误数据中，需要操作取消发单重新使用新协议发单；存在待发单数据，不允许更换协议，可直接使用关联协议功能关联最新协议发单。
            </p>
          </StepItem>
          <FileUpload
            title="上传文件"
            currentStep={currentStep}
            setCurrentstep={this.setCurrentstep}
            downloadTempInfo={{
              // 下载模板信息
              params: { fileId, fileName },
              url: '/csApi/batchTask/downloadFile',
            }}
            uploadFile={this.uploadFile}
            uploading={uploading}
            // 展示进度条需要的数据
            maskClosable
            progressPercent={progressPercent || 0}
            progressTitle="更换协议任务"
            progressVisible={showProgress}
            preStep={() => {
              this.setCurrentstep(currentStep - 1);
              dispatch({
                type: 'changeprot/updateModelData',
                payload: {
                  isGoBack: true,
                },
              });
              router.push(`/sendordermanage/adjusttask/changeprotocol`);
            }}
          />
          <Finish title="完成" resultInfo={resultInfo} setCurrentstep={this.setCurrentstep} />
        </BatchUpload>
      </PageHeaderWrapper>
    );
  }
}

export default Batch;
